package com.miniso.robot;

import com.miniso.robot.bean.Message;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author guojunwang
 * @date 2021-10-18 20:17
 */
@Component
public class MessageUtil implements ApplicationContextAware {


    public static ApplicationContext appContext;

    public static void sendMessage( String robotKey,Message message ){
        RestTemplate restTemplate = appContext.getBean(RestTemplate.class);
        String webhookUrl = appContext.getBean(Environment.class).getProperty("robot.webhook.url");

        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("key", robotKey);
        paramMap.add("msg",message);


        // 2、使用postForEntity请求接口
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity(paramMap,headers);


        restTemplate.postForObject(webhookUrl+"?key={key}",httpEntity,String.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MessageUtil.appContext = applicationContext;
    }
}
